package org.link.util;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * project_name:forumweb
 * package_name:org.link.util
 * file_name:CodeServlet.java
 * @author Link
 * create_date:2015年10月24日上午9:58:00
 * modified_date:
 * description: 验证码servlet
 *
 */
public class CodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		//System.out.println(request.getHeader("Host"));
		//System.out.println(request.getHeader("Referer"));
		char[] ch = {'1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j'};
		Random random = new Random();
		BufferedImage image = new BufferedImage(50, 30, BufferedImage.TYPE_INT_BGR);
		Graphics g = image.getGraphics();
		StringBuffer buffer = new StringBuffer("");
		for(int i = 0;i<5;i++){
			int index = random.nextInt(ch.length);
			buffer.append(ch[index]);
		}
		session.setAttribute("imageCode", buffer.toString()); //存储到session中以便后面回传值进行判断
		g.drawString(buffer.toString(), 9, 18); //画图
		ImageIO.write(image, "png", response.getOutputStream()); //返回

		
	}

}
